#include "../HttpRequest.h"
using namespace yhaida;

HttpRequest::HttpRequest()
    : _method(Method::kInvalid),
      _version(Version::kUnknown)
{
}

void HttpRequest::setVersion(Version v)
{
    _version = v;
}
HttpRequest::Version HttpRequest::getVersion() const
{
    return _version;
}

bool HttpRequest::setMethod(const char *start, const char *end)
{
    assert(_method == kInvalid);
    std::string cmd(start, end);
    if (cmd == "GET")
    {
        _method = kGet;
    }
    else if (cmd == "POST")
    {
        _method = kPost;
    }
    else if (cmd == "HEAD")
    {
        _method = kHead;
    }
    else if (cmd == "PUT")
    {
        _method = kPut;
    }
    else if (cmd == "DELETE")
    {
        _method = kDelete;
    }
    else
    {
        _method = kInvalid;
    }
    return _method != kInvalid;
}
HttpRequest::Method HttpRequest::method() const
{
    return _method;
}
const char *HttpRequest::methodString() const
{
    const char *result = "UNKNOWN";
    switch (_method)
    {
    case kGet:
        result = "GET";
        break;
    case kPost:
        result = "POST";
        break;
    case kHead:
        result = "HEAD";
        break;
    case kPut:
        result = "PUT";
        break;
    case kDelete:
        result = "DELETE";
        break;
    default:
        break;
    }
    return result;
}

void HttpRequest::setPath(const char *start, const char *end)
{
    _path.assign(start, end);
}
const std::string &HttpRequest::path() const
{
    return _path;
}
void HttpRequest::setQuery(const char *start, const char *end)
{
    _query.assign(start, end);
}
const std::string &HttpRequest::query() const
{
    return _query;
}

void HttpRequest::setReceiveTime(Timestamp t)
{
    _receiveTime = t;
}
Timestamp HttpRequest::receiveTime() const
{
    return _receiveTime;
}

// Host: www.itcast.cn
// ...
void HttpRequest::addHeader(const char *start, const char *colon, const char *end)
{

    std::string field(start, colon);
    ++colon;
    while (colon < end && isspace(*colon)) //跳过空格
    {
        ++colon;
    }
    std::string value(colon, end);
    while (!value.empty() && isspace(value[value.size() - 1])) //去除尾部的空格
    {
        value.resize(value.size() - 1);
    }
    _headers[field] = value;
}
std::string HttpRequest::getHeader(const std::string &field) const
{
    std::string result;
    auto it = _headers.find(field);
    if (it != _headers.end())
    {
        result = it->second;
    }
    return result;
}
const std::map<std::string, std::string> &HttpRequest::headers() const
{
    return _headers;
}
void HttpRequest::setBody(std::string body)
{
    _body = std::move(body);
}
const std::string HttpRequest::getBody() const
{
    return _body;
}

void HttpRequest::swap(HttpRequest &that)
{
    std::swap(_method, that._method);
    std::swap(_version, that._version);
    _path.swap(that._path);
    _query.swap(that._query);
    _receiveTime.swap(that._receiveTime);
    _headers.swap(that._headers);
}